package com.core.dao.jdbcmysql;

import com.core.bean.Goods;
import com.core.bean.Shipments;
import com.core.bean.UserAddress;
import com.core.dao.BaseDao;
import com.core.dao.IShipmentsDao;
import com.core.utils.GsonUtils;
import com.google.gson.Gson;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;

public class ShipmentsDao extends JdbcBase implements IShipmentsDao {
    @Override
    public int add(Shipments entity) throws Exception {

        String Sql = "INSERT INTO `lct_shipments` VALUES(?,?,?,?,?,?,?) ";
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(Sql);
        try {
            preparedStatement.setString(1, entity.getId());
            preparedStatement.setObject(2, GsonUtils.toJsonStr(entity.getGoods()));
            preparedStatement.setString(3, entity.getConsignor());
            preparedStatement.setString(4, entity.getShipAddress());
            preparedStatement.setObject(5, entity.getShipTime());
            preparedStatement.setInt(6, entity.getStatus());
            preparedStatement.setString(7, GsonUtils.toJsonStr(entity.getUserAddress()));
            return preparedStatement.executeUpdate();
        } catch (Exception e) {
            System.err.println("插入失败");
            throw e;
        } finally {
            preparedStatement.close();
            connection.close();
        }
    }

    @Override
    public int remove(String id) throws Exception {
        return 0;
    }

    @Override
    public int modify(Shipments entity) throws Exception {
        return 0;
    }

    @Override
    public Shipments findEntityById(String id) throws Exception {
        String Sql = "SELECT * FROM `lct_shipments` WHERE id =?";
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(Sql);
        preparedStatement.setString(1, id);
        ResultSet resultSet = preparedStatement.executeQuery();
        Shipments shipments = null;
        while (resultSet.next()) {
            String Myid = resultSet.getString("id");
            String goods = resultSet.getString("goods");
            Goods goods1 = GsonUtils.fromJson(goods, Goods.class);
            String consignor = resultSet.getString("consignor");
            String ship_address = resultSet.getString("ship_address");
            Date ship_time = resultSet.getDate("ship_time");
            String user_address = resultSet.getString("user_address");
            UserAddress userAddress = GsonUtils.fromJson(user_address, UserAddress.class);
            int status = resultSet.getInt("status");
            shipments = new Shipments(Myid, goods1, consignor, ship_address, userAddress, ship_time, status);
        }
        return shipments;
    }
}
